package com.xd.clap.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xd.clap.entity.Product;
import com.xd.clap.entity.request.PageParam;
import com.xd.clap.entity.response.Result;
import com.xd.clap.mapper.ProductMapper;
import com.xd.clap.services.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper pm;


    @Override
    public Result getProductPage(PageParam pageParam) {
        IPage<Product> iPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (pageParam.getId() >= 0) {
            queryWrapper.eq("cid", pageParam.getId());
        }
        if (!StringUtils.isBlank(pageParam.getMessage())) {
            queryWrapper.like("name", pageParam.getMessage());
        }
        queryWrapper.orderByDesc("is_show");
        queryWrapper.orderByAsc("cid", "id");
        IPage<Product> products = pm.selectPage(iPage, queryWrapper);
        return Result.success(products, "加载成功!");
    }

    @Override
    public Result updateShow(Product product) {
        boolean isShow = product.getIsShow();
        int id = product.getId();
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("is_show", isShow);
        int update = pm.update(null, updateWrapper);
        if (update < 1) {
            return Result.fail(0, "更新失败");
        }

        return Result.success(update, "更新成功！");
    }


    @Override
    public Result getProductById(int id) {
        Product product = pm.selectById(id);
        return Result.success(product, "加载成功");
    }


    @Override
    public Result updateProduct(Product product) {
        if (product.getId() == null) {
            int insert = pm.insert(product);
            if (insert < 1) {
                return Result.fail(0, "添加失败！");
            }
            return Result.success(insert, "添加成功！");
        } else {
            int update = pm.updateById(product);
            if (update < 1) {
                return Result.fail(0, "更新失败！");
            }
            return Result.success(update, "更新成功！");
        }
    }

    @Override
    public Result deleteProduct(int id) {
        int delete = pm.deleteById(id);
        if (delete < 1) {
            return Result.fail(0, "删除失败！");
        }
        return Result.success(delete, "删除成功！");
    }

  


}
